import { intersection } from 'lodash-es'
import { usePermissionStore } from '@/store/modules/permission'
import { isArray } from '@/utils/is'

// User permissions related operations
export function usePermission() {
  const permissionStore = usePermissionStore()

  /**
   * Determine whether there is permission
   */
  function hasPermission(value: string | string[] | undefined, def = true): boolean {
    // Visible by default
    if (!value)
      return def

    const allCodeList = permissionStore.getComponentCodes as string[]
    if (!isArray(value))
      return allCodeList.includes(value)

    return intersection(value, allCodeList).length > 0
  }

  return { hasPermission }
}
